/* 
 * File:   JEpoll.cpp
 * Author: johnneyshi
 * 
 * Created on 2013年3月3日, 下午12:21
 */

#include "JEpoll.h"
#include "JException.h"

JEpoll::JEpoll() : epollHandler(0),maxFdCount(0),pEvents(NULL)
{
    
}

void JEpoll::AddFd(int fd)
{
    struct epoll_event ev;
    ev.events = EPOLLIN | EPOLLET;
    ev.data.fd = fd;
    if(epoll_ctl(epollHandler,EPOLL_CTL_ADD,fd,&ev) < 0)
    {
        throw JException("epoll_ctl add error.");
    }
}

void JEpoll::Create(int fdCount)
{
    maxFdCount = fdCount;
    epollHandler = epoll_create(fdCount);
    pEvents = new struct epoll_event[fdCount];
    if(pEvents == NULL)
    {
        throw JException("new struct epoll_event error.");
    }
}

std::vector<int> JEpoll::Wait()
{
    std::vector<int> sockFds;
    int eventCount = epoll_wait(epollHandler,pEvents,maxFdCount,-1);
    for(int i = 0;i < eventCount; ++i)
    {
        sockFds.push_back(pEvents[i].data.fd);
    }
    return sockFds;
}

void JEpoll::DeleteFd(int fd)
{
    struct epoll_event ev;
    ev.events = EPOLLIN | EPOLLET;
    ev.data.fd = fd;
    if(epoll_ctl(epollHandler,EPOLL_CTL_DEL,fd,&ev) < 0)
    {
        throw JException("epoll_ctl delete error.");
    }
}

JEpoll::~JEpoll() 
{
    if(pEvents != NULL)
    {
        delete [] pEvents;
    }
}

